package com.bangcommunity.bbframe.sdm.web.shiro.filter;

import com.bangcommunity.bbframe.common.utils.lang.StringUtils;
import com.bangcommunity.bbframe.sdm.utils.RequestUtils;
import com.bangcommunity.bbframe.sdm.web.exception.RestConf;
import com.bangcommunity.bbframe.sdm.web.shiro.BaseSdmAuthenticationToken;
import com.bangcommunity.bbframe.sdm.web.shiro.ISdmWebTokenService;
import com.bangcommunity.bbframe.sdm.web.shiro.realm.IShiroUser;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 基于Shiro 实现的SSO登陆认证的Filter
 *
 * @version 1.0
 * @author tanghc
 */
public class BaseSdmTokenAuthenticationFilter<PK extends Serializable>
        extends AbstractSdmTokenAuthenticationFilter<PK, BaseSdmAuthenticationToken> {

    @Autowired(required = false)
    private ISdmWebTokenService<PK> sdmWebTokenService;

    @Override
    protected BaseSdmAuthenticationToken createSdmToken(HttpServletRequest request, HttpServletResponse response) {
        String extractParam = RequestUtils.extractParam(request, RestConf.tokenKey);
        if (StringUtils.isBlank(extractParam)) {
            logger.error("create sdm token fail no sso_access_token");
            return null;
        }
        BaseSdmAuthenticationToken token = new BaseSdmAuthenticationToken();
        token.setSsoToken(extractParam);
        return token;
    }

    @Override
    protected boolean validToken(PK uid, String token) {
        return sdmWebTokenService.validToken(uid, token);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
            ServletResponse response) throws Exception {
        boolean b = super.onLoginSuccess(token, subject, request, response);
        if (null != subject) {
            IShiroUser<PK> shiroUser = (IShiroUser<PK>) subject.getPrincipal();
            if (null != shiroUser && StringUtils.isNotBlank(shiroUser.getToken())) {
                Cookie cookie = new Cookie(RestConf.tokenKey, shiroUser.getToken());
                cookie.setPath("/");
                ((HttpServletResponse) response).addCookie(cookie);
                ((HttpServletResponse) response).addHeader(RestConf.tokenKey, shiroUser.getToken());
            }
        }
        return b;
    }
}
